#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 19-6-26 上午9:52
# @Author  : Tom
# @Site    : 
# @File    : brands.py
# @Software: PyCharm
from pprint import pprint
from django.conf import settings
# from fdfs_client.client import Fdfs_client
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from goods.models import Brand, SKUImage
from meiduo_admin.serilizers import GoodsBrandsSerilizer
from meiduo_admin.utils import PageNumber_User
from meiduo_mall.utils.response_code import RETCODE


class GoodsBrandsView(ModelViewSet):
    serializer_class = GoodsBrandsSerilizer
    queryset = Brand.objects.all()
    pagination_class = PageNumber_User
    permission_classes = [IsAdminUser]

    def create(self, request, *args, **kwargs):
        file = request.FILES.get("logo")
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        fdfs = Fdfs_client(settings.FDFS_PATH)
        answer = fdfs.upload_appender_by_buffer(file.read())
        if answer['Status'] != 'Upload successed.':
            return Response({"code": RETCODE.DBERR, "errmsg": "图片保存错误！"})
        path = answer['Remote file_id']
        # 3.保存到数据库
        brand = Brand.objects.create(name=name, logo=path, first_letter=first_letter)
        ser = GoodsBrandsSerilizer(brand)
        # 4.返回前端保存对象
        return Response(ser.data, status=201)

    def update(self, request, *args, **kwargs):
        file = request.FILES.get("logo")
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')

        fdfs = Fdfs_client(settings.FDFS_PATH)
        answer = fdfs.upload_appender_by_buffer(file.read())
        if answer['Status'] != 'Upload successed.':
            return Response({"code": RETCODE.DBERR, "errmsg": "图片保存错误！"})
        path = answer['Remote file_id']
        brand = self.get_object()
        brand.name = name
        brand.logo = path
        brand.first_letter = first_letter
        brand.save()
        ser = GoodsBrandsSerilizer(brand)
        # 4.返回前端保存对象
        return Response(ser.data, status=201)
